﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using NetCore.WebApi.AOP;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace NetCore.WebApi.SetUp
{
    public class AutofacModuleRegister : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            //注册RedisAop
            builder.RegisterType<RedisCacheAOP>();
            //注册Service
            var assemblysServices = Assembly.Load("NetCore.Services");
            builder.RegisterAssemblyTypes(assemblysServices)
                .InstancePerDependency()//瞬时单例
               .AsImplementedInterfaces()////自动以其实现的所有接口类型暴露（包括IDisposable接口）
               .EnableInterfaceInterceptors() //引用Autofac.Extras.DynamicProxy;
               .InterceptedBy(typeof(RedisCacheAOP));//可以放一个AOP拦截器

            //注册Repository
            var assemblysRepository = Assembly.Load("NetCore.Repository");
            builder.RegisterAssemblyTypes(assemblysRepository)
                .InstancePerDependency()//瞬时单例
               .AsImplementedInterfaces()////自动以其实现的所有接口类型暴露（包括IDisposable接口）
               .EnableInterfaceInterceptors(); //引用Autofac.Extras.DynamicProxy;

            //注册LogAOP
            var basePath = AppContext.BaseDirectory;
            var bllFilePath = Path.Combine(basePath, "NetCore.Services.dll");
            List<Type> aops = new List<Type>();
            builder.RegisterType<LogAOP>();
            aops.Add(typeof(LogAOP));
            //BLL层注册服务
            builder.RegisterAssemblyTypes(Assembly.LoadFile(bllFilePath))
                .AsImplementedInterfaces()
                .InstancePerDependency()
                .EnableInterfaceInterceptors()
                .InterceptedBy(aops.ToArray());//注册拦截器
        }
    }
}